/**
 * ************************************ 框架公共工具方法封装
 */

/**
 * 格式化对象
 */
export const formatObject = (obj, keys) => {
    const res = {};
    keys.forEach(key => {
        res[key] = obj[key];
    });
    return res;
};

/**
 * 转化为 FormData
 */
export const convertToFormData = data => {
    const formData = new FormData();
    for (let key in data) {
        formData.append(key, data[key]);
    }
    return formData;
};

/**
 * 页面锚点跳转
 */
export const navigateToAnchor = id => {
    location.href =
        location.href.indexOf("#") > -1
            ? location.href
            : location.href + "#" + id;
};

export const config = {
    isIOS() {
        return navigator.userAgent && /iphone|ipad/i.test(navigator.userAgent);
    },
    scrollTo(x, y) {
        window.scrollTo({
            top: y,
            left: x,
        });
    },
    fixIOSKeyboard() {
        document.body.addEventListener("focusout", () => {
            const currentPosition =
                document.documentElement.scrollTop || document.body.scrollTop;
            setTimeout(() => {
                this.scrollTo(0, currentPosition + 1);
                this.scrollTo(0, currentPosition - 1);
            }, 100);
        });
    },
};

export const checkTypes = {
    isObject(data) {
        return typeof data === "object" && data !== null;
    },
};

export const getTodayTimeRange = () => {
    const t = new Date();
    const year = t.getFullYear();
    const month = t.getMonth();
    const date = t.getDate();
    // const start = new Date(`${year}-${month}-${date} 00:00:00 GMT`);
    const start = new Date(year, month, date);
    // const end = new Date(`${year}-${month}-${date} 23:59:59 GMT`);
    const end = new Date(year, month, date + 1);
    return [start, end];
};

export const getCurrentMonthTimeRange = () => {
    const t = new Date();
    const year = t.getFullYear();
    const month = t.getMonth() + 1;
    const date = t.getDate();
    const start = new Date(`${year}-${month}-${1} 00:00:00 GMT`);
    const end = new Date(`${year}-${month}-${date} 23:59:59 GMT`);
    return [start, end];
};
